package com.easy.easybanner.view;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sigthp-P-Department on 2018/4/25.
 */

public class EasyBannerViewPager extends ViewPager{


    private static final int ROLL_MESSAGE = 1;
    private EasyPagerAdapter mEasyPagerAdapter;

    private int mDuration;
    private EasyScroller scroller;
    private RollHandle rollHandle;
    private List<View> mConvertViews=new ArrayList<>();


    public EasyBannerViewPager(Context context) {
        this(context,null);
    }

    public EasyBannerViewPager(Context context, AttributeSet attrs)  {
        super(context, attrs);
        try {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            scroller = new EasyScroller(context);
            field.set(this,scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public View getConvertView() {
        for (View mConvertView : mConvertViews) {
            if(mConvertView.getParent()==null){
                return mConvertView;
            }
        }
        return null;
    }

    private static class RollHandle extends Handler{

        private WeakReference<EasyBannerViewPager> weakReference;

        public RollHandle(EasyBannerViewPager easyBannerViewPager){
            weakReference = new WeakReference<>(easyBannerViewPager);
        }
        @Override
        public void handleMessage(Message msg) {
            weakReference.get().setCurrentItem(weakReference.get().getCurrentItem() + 1);
            weakReference.get().setAutomaticRolling();
        }
        public void clearWeakReference(){
            weakReference.clear();
            weakReference=null;
        }
    }

    private Application.ActivityLifecycleCallbacks lifecycleCallbacks=new DefaultApplicationLeftcycleCallBack(){
        @Override
        public void onActivityResumed(Activity activity) {
            super.onActivityResumed(activity);
            if (activity==getContext()){
                rollHandle.sendEmptyMessageDelayed(ROLL_MESSAGE,mDuration);
            }

        }

        @Override
        public void onActivityPaused(Activity activity) {
            super.onActivityPaused(activity);
            if (activity==getContext()){
                rollHandle.removeMessages(ROLL_MESSAGE);
            }

        }
    };

    public EasyBannerViewPager setEasyPagerAdapter(EasyPagerAdapter easyPagerAdapter) {
        this.mEasyPagerAdapter = easyPagerAdapter;
        setAdapter(new BannerViewPagerAdapter());
        ((Activity)getContext()).getApplication().registerActivityLifecycleCallbacks(lifecycleCallbacks);
        return this;
    }
    public EasyBannerViewPager setDuration(int duration) {
        this.mDuration = duration;
        return this;
    }
    public EasyBannerViewPager setScrollerDuration(int duration){
        scroller.setmDuration(duration);
        return this;
    }
    public EasyBannerViewPager setAutomaticRolling(){
        if(rollHandle==null){
            rollHandle = new RollHandle(this);
        }
        rollHandle.removeMessages(ROLL_MESSAGE);
        rollHandle.sendEmptyMessageDelayed(ROLL_MESSAGE,mDuration);
        return this;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        rollHandle.removeMessages(ROLL_MESSAGE);
        rollHandle.clearWeakReference();
        rollHandle = null;
        ((Activity)getContext()).getApplication().unregisterActivityLifecycleCallbacks(lifecycleCallbacks);
    }

    private class BannerViewPagerAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = mEasyPagerAdapter.getView(position % mEasyPagerAdapter.getCount(), getConvertView());
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            mConvertViews.add((View) object);
        }
    }
}
